package cn.li.simplemotionblurdemo;

import android.graphics.Bitmap;
import android.graphics.Color;

/**
 * Created by li on 17-8-1.
 */

public class ImageUtil {
    public static Bitmap motionblurd(Bitmap bitmap, int arg1, double arg2) {
        if (arg1 == 0)
            return bitmap;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int _width = width + arg1;
        int pixels[] = new int[width * height];
        int offset = (int) (arg1 * arg2);
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
        bitmap.recycle();
        bitmap = null;

        int _pixels[] = new int[_width * height];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < _width; j++) {

                int position = i * _width + j;

                int alpha = 0;
                int red = 0;
                int green = 0;
                int blue = 0;

                int count = 0;

                for (int k = position - offset; k < position + arg1 - offset; k++) {
                    if (k >= 0 && k / _width == i && k % _width >= offset && k % _width < offset + width) {
                        int _position = i * width + k % _width - offset;
                        alpha += Color.alpha(pixels[_position]);
                        red += Color.red(pixels[_position]);
                        green += Color.green(pixels[_position]);
                        blue += Color.blue(pixels[_position]);
                        count++;
                    }
                }
                if (count!=0)
                _pixels[position] = Color.argb(alpha / arg1, red / count, green / count, blue / count);
            }
        }
        return Bitmap.createBitmap(_pixels, _width, height, Bitmap.Config.ARGB_8888);
    }
}
